// 拓扑图预览
angular.module('HTRD_AutoConsole.A').directive('quneeInfoHistory',['$window', '$timeout', '$interval', '$stateParams', '$rootScope', 'ManagerProcessQuneeServ', 'DialogServ', 'SocketServ', 'AlertServ', 'ParseMapServ', 'DateParseServ',
function($window, $timeout, $interval, $stateParams, $rootScope, ManagerProcessQuneeServ, DialogServ, SocketServ, AlertServ, ParseMapServ, DateParseServ) {
  var link = function(s, e) {
      var $scope, $node, testCount = 0;
      var quneeStart, strapModal;

      // 流程id
      var processId = 0;

      var execId = 0;

      // 执行id
      var execId;

      var nodeStatusMap = {
        // -1: 'st_unknow',  # 未知状态

        // 流程初始化
        0: 'init'
        ,
        // # 正在检测
        1: 'check',

        // # 流程检测错误
        2: 'checkError',

        // # 节点检测－脚本错误
        3: 'checkScriptError',

        // # 节点检测－主机错误
        4: 'checkError',

        // # 检测成功
        5: 'checkSuccess',

        // # 正在执行
        6: 'running',

        // # 执行错误
        7: 'runError',

        // # 执行超时
        8: 'runTimeout',

        // # 执行成功
        9: 'runSuccess',

        // # 等待用户确认
        10: 'waitUserConfirm',

        // # 停止执行
        11: 'quit',

        // # 正在停止
        12: 'st_stopping',

        // # 暂停执行
        13: 'pause',

        // # 正在暂停
        14: 'st_pausing',

        // # 等待用户输入
        15: 'st_waiting_for_input',

        // # 执行单个节点/重做
        16: 'st_running_one',

        // # 执行单个节点/重做 成功
        17: 'st_run_one_ok',

        // # 执行单个节点/重做 失败
        18: 'st_run_one_err',

        // # 用户拒绝
        19: 'st_confirm_refused',

        // 执行完成但有错误
        20: 'runSuccessAndNodeError',

        // 手工接管后的执行结果：成功
        21: 'takeOverSucc',

        // 手工接管后的执行结果：失败
        22: 'takeOverError'
      };

      // 如果状态为数字 则转换
      var quneeStateMap = {
        0: 'init', // 默认(1级分类)
        1: 'check', // 检测中(1级分类)
        2: 'exec', // 执行中(1级分类)
        3: 'checkError', // 检测异常(2级分类)
        4: 'checkSuccess', // 检测成功(2级分类)
        5: 'execSuccess' // 执行成功
      };

      // 执行中状态
      var runningMap = {
        0: 'pause',
        1: 'running'
      };

      // 执行中节点状态
      var runningNodeMap = {
        0: 'error',
        1: 'overtime',
        2: 'runningSuccess'
      };

      var quneeRefTypeMap = {
        1: 'basicNode',
        2: 'userConfirmNode',
        3: 'groupNode',
        4: 'startNode',
        5: 'endNode',
        6: 'closeNode',
        7: 'restartNode'
      };

      // 转换json字符串 , 组装完整的json数据
      // var quneeParseNodeJSON = function(nodeList, nodeStatusList) {
      //   var nodeJSON;
      //
      //   if (typeof nodeList === 'string') {
      //     nodeJSON = JSON.parse(nodeList);
      //   } else {
      //     nodeJSON = nodeList;
      //   };
      //
      //   // 判断节点状态列表内是否有数据 没有则代表初始化状态
      //   if (!!nodeStatusList) {
      //     nodeStatusList.map(function(item) {
      //
      //       for (var key in nodeJSON) {
      //         nodeJSON[key].map(function(node) {
      //
      //           if (node.id === item.node_id) {
      //             node.infoData.status = nodeStatusMap[item.status] || 'init';
      //           } else {
      //             node.infoData.status = 'init';
      //           };
      //
      //           node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
      //         });
      //       };
      //     });
      //   } else {
      //
      //     for (var key in nodeJSON) {
      //       nodeJSON[key].map(function(node) {
      //         node.infoData.status = 'init';
      //         node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
      //       });
      //     };
      //   };
      //   return nodeJSON;
      // };

      var quneeParseNodeJSON = function(nodeList, nodeStatusList) {
        var nodeJSON;

        if (typeof nodeList === 'string') {
          nodeJSON = JSON.parse(nodeList);
        } else {
          nodeJSON = nodeList;
        };

        console.log('quneeParseNodeJSON');
        console.log(nodeJSON);
        console.log(nodeStatusList);

        // 判断节点状态列表内是否有数据 没有则代表初始化状态
        if (!!nodeStatusList) {

          for (var key in nodeJSON) {

            if (key === 'groups') {
              nodeStatusList.map(function(item) {
                nodeJSON[key].map(function(group) {

                  // 循环组内的节点状态
                  group.nodes.map(function(node) {

                    if (node.id === (item.node_id || item.id)) {
                      node.infoData.status = nodeStatusMap[item.status] || 'init';
                    };

                    node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
                  });
                });
              });
            } else {
              nodeStatusList.map(function(item) {
                nodeJSON[key].map(function(node) {

                  if (node.id === (item.node_id || item.id)) {
                    node.infoData.status = nodeStatusMap[item.status] || 'init';
                  };

                  node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
                });
              });
            }
          };
        } else {

          for (var key in nodeJSON) {
            nodeJSON[key].map(function(node) {
              node.infoData.status = 'init';
              node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
            });
          };
        };
        return nodeJSON;
      };

      var resetNodes = function() {
        var refId;
        $scope.nodeList = quneeParseNodeJSON($scope.pipeline);

        // 先获取全部node
        selfJson = JSON.parse($scope.getChartJSON());
        selfJson.datas.map(function(selfItem, index) {

          // 更新普通节点
          if (selfItem._className === 'Q.Node') {

            if (!!!selfItem.json.properties.data.id) {
              refId = selfItem.json.properties.data.$ref;
              selfItem.json.properties.data = selfJson.refs[refId];
            };

            selfItem.json.properties.data.infoData.status = 'init';
            getNodeData(selfItem.json.properties.data, selfItem.json);
          };
        });

        updateJSON(selfJson);
      };

      var updateQuneeStateBtn = function() {
        $node.find('.htrd-c-button-group').eq(0).hide();
      };

      var socketPullData = function(data) {
        $node.trigger('qunee.stateChange', data);
      };

      var getQuneeNodeInfo = function(data) {
        $scope.$apply(function () {
          $scope.historyListState = false;
          $scope.processInfoState = false;
          $scope.nodeInfoState = true;
        });
      };

      var getQuneeProcessInfo = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeInfo({
          id: processId
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.processInfo = ret.results;
          } else {

          };
        });
      };

      var getQuneeHistoryList = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeHistoryList({
          id: processId
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.historyList = ret.results;
          } else {
            $scope.historyList = [];
            AlertServ.showError(ret.msg);
          };
        });
      };

      var getUserList = function() {
        ManagerProcessQuneeServ.getUserList()
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.userList = [];
            ret.results.data.map(function(item, index) {
              $scope.userList.push({
                id: item.id,
                title: item.username
              });
            });
          }
        });
      };

      var activeUser = function(item) {
        $scope.userConfirmModel.userId = item.id;
      };

      // 用户用户确认/重做弹框
      var submitUserConfirm = function() {

        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.submotManagerProcessQuneeUserConfirm($scope.userConfirmModel)
        .then(function(ret) {

          if (ret.status === 200) {
            AlertServ.showSuccess(ret.msg);
            strapModal.hide();
            $scope.userConfirmModel = {
              errerMsg: '提示：用户确认超时2分钟。'
            };
            $scope.selectDefaultText = '请选择用户';
            $scope.quneeState = 'running';
            $timeout(function() {
              $scope.socketPullData($scope.quneeState);
              updateQuneeStateBtn();
            }, 2000);
          } else {
            $scope.userConfirmModel.errerMsg = ret.msg || '密码错误, 请重试';
            // AlertServ.showError();
          };
        });
      };

      // 用户接管
      var submitEditorTakeOver = function() {

        var data = {
          // id: $scope.userEditorTakeOverModel.id,
          id: execId,
          result_status: $scope.userEditorTakeOverModel.check,
          result_info: $scope.userEditorTakeOverModel.remark.trim()
        };
        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.ManagerProcessQuneeManualNozzleNode(data)
        .then(function(ret) {

          if (ret.status === 200) {
            AlertServ.showSuccess(ret.msg);
            strapModal.hide();
            $scope.userEditorTakeOverModel = {};
            $scope.quneeState = 'manualQuit';
            updateQuneeStateBtn();

            if (!$node.find('.qunee-start').is(":hidden")) {
              ParseMapServ.setItem(processId, 'start', 'quitState');
            };

            if (!$node.find('.qunee-continue').is(":hidden")) {
              ParseMapServ.setItem(processId, 'continue', 'quitState');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              ParseMapServ.setItem(processId, 'pause', 'quitState');
            };

            $timeout(function() {
              $scope.socketPullData('quit');
            }, 2000);
          } else {
            AlertServ.showError(ret.msg);
          }
        });
      };

      // 手动终止确认
      var submitProcessQuit = function() {
        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.ManagerProcessQuneeQuit({
          id: execId,
          result_info: $scope.userEditorQuitModel.remark
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.userEditorQuitModel = {};
            strapModal.hide();
            $timeout.cancel(quneeStart);
            $scope.quneeState = 'manualQuit';

            if (!$node.find('.qunee-start').is(":hidden")) {
              ParseMapServ.setItem(processId, 'start', 'quitState');
            };

            if (!$node.find('.qunee-continue').is(":hidden")) {
              ParseMapServ.setItem(processId, 'continue', 'quitState');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              ParseMapServ.setItem(processId, 'pause', 'quitState');
            };

            updateQuneeStateBtn();
            AlertServ.showSuccess(ret.msg);
            $timeout(function() {
              $scope.socketPullData('quit');
            }, 2000);
          } else {
            AlertServ.showError(ret.msg);
          };
        });
      };

      var getManagerProcessQuneeLogList = function(processId) {
        console.log('execId',execId)
        ManagerProcessQuneeServ.getManagerProcessQuneeLogList({
          // id: 100
          id: execId
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.logList = ret.results;
            $scope.logList.map(function(item, index) {
              item.created_at = DateParseServ.dateParse(item.created_at);
            });
            // AlertServ.showSuccess(ret.msg);
          } else {
            AlertServ.showError(ret.msg);
          };
        });
      };

      // 获取当前流程节点json数据以及状态
      var getQuneeStateAndData = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeStateAndData({
          id: processId
        })
        .then(function(ret) {
          var quneeState;

          console.log('历史执行');

          if (ret.status === 200) {

            // 获取1级状态 0 基本 1 检测中 2 执行中
            quneeState = ret.results.status;

            // 只可能是执行完的策略才能进
            // if (quneeState === 0) {

            if (!!ret.results.checked) {
              $scope.init = true;
              $scope.lastCheckDateStr = '上次检测时间: ' + ret.results.checked.ended_at.replace('T', ' ').replace('Z','');
              $scope.lastCheckStatus = ret.results.checked.status;
              $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline);
              // $scope.initEditor();

              if (typeof ret.results.checked.status === 'number') {
                $scope.quneeState = quneeStateMap[ret.results.checked.status];
              } else {
                $scope.quneeState = ret.results.checked.status || 'init';
              };

              // 获取执行的状态
              $scope.getQuneeExecState($scope.nodeList);
            } else {
              $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline);
              $scope.initEditor();
              $scope.quneeState = 'init';
            };
            updateQuneeStateBtn();
            // }
          };
        });
      };

      // 获取执行的具体状态
      var getQuneeExecState = function(pipeline) {
        ManagerProcessQuneeServ.getManagerProcessQuneeExecState({
          id: execId
        })
        .then(function(ret) {

          if (ret.status === 200) {
            console.log('ret.results', ret.results);
            console.log('最后执行状态 ret.results.result_status', ret.results.result_status);
            var statusStr = nodeStatusMap[ret.results.result_status];

            if (ret.results.exec_nodes) {
              $scope.nodeList = quneeParseNodeJSON(pipeline, ret.results.exec_nodes);
            } else {
              $scope.nodeList = [];
            };

            console.log('$scope.nodeList', $scope.nodeList);

            $scope.initEditor(function() {
              console.log('statusStr', statusStr);
              $scope.socketPullData(statusStr);
              $node.find('.qunee-history').hide();
            });

            updateQuneeStateBtn();
            // resetNodes();
          }
        });
      };

      // 获取流程节点
      var getQuneeState = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeState()
        .then(function(result) {

          if (result.status === 200) {
            $scope.quneeState = result.results.state;
            updateQuneeStateBtn();
          };
        });
      };

      var onStateChange = function(evt, data) {
        console.log('$scope.quneeState', data);

        // 所有标识状态的集合
        // 所有标识状态的集合
        var tagStatusMap = {
          requesting: {
            status: 'qunee-status label label-info bg-blue',
            text: '正在请求中'
          },

          check: {
            status: 'qunee-status label label-info bg-blue',
            text: '流程检测中'
          },

          checkSuccess: {
            status: 'qunee-status label label-success bg-green',
            text: '检测成功'
          },

          checkError: {
            status: 'qunee-status label label-danger',
            text: '检测异常'
          },

          running: {
            status: 'qunee-status label label-info bg-blue',
            text: '流程执行中'
          },

          runError: {
            status: 'qunee-status label label-danger',
            text: '检测异常'
          },

          pause: {
            status: 'qunee-status label label-info bg-blue',
            text: '流程已暂停'
          },

          parseError: {
            status: 'qunee-status label label-danger',
            text: '检测异常'
          },

          st_pausing: {
            status: 'qunee-status label label-info bg-blue',
            text: '流程已暂停'
          },

          continue: {
            status: 'qunee-status label label-info bg-blue',
            text: '流程执行中'
          },

          quit: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止'
          },

          manualQuit: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止'
          },

          st_stopping: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止'
          },

          runSuccess: {
            status: 'qunee-status label label-success bg-green',
            text: '流程执行成功'
          },

          runSuccessAndNodeError: {
            status: 'qunee-status label label-danger',
            text: '流程执行成功但节点有错误'
          },

          noApproval: {
            status: 'qunee-status label label-danger',
            text: '不认可'
          },

          takeOverSucc: {
            status: 'qunee-status label label-success bg-green',
            text: '手工接管后的执行结果：成功'
          },

          takeOverError: {
            status: 'qunee-status label label-danger',
            text: '手工接管后的执行结果：失败'
          },

          waitUserConfirm: {
            status: 'qunee-status label label-info bg-blue',
            text: '等待用户确认'
          },

          st_confirm_refused: {
            status: 'qunee-status label label-danger',
            text: '被不认可终止'
          },

          // 执行完成但有错误
          runSuccessAndNodeError: {
            status: 'qunee-status label label-danger',
            text: '执行完成但有错误'
          },

          takeOverSucc: {
            status: 'qunee-status label label-success bg-green',
            text: '手工接管后的执行结果：成功'
          },

          takeOverError: {
            status: 'qunee-status label label-danger',
            text: '手工接管后的执行结果：失败'
          }
        };

        if (!!tagStatusMap[data]) {
          var status = tagStatusMap[data].status;
          var text = tagStatusMap[data].text;
          $node.find('.qunee-status').removeClass().addClass(status);
          $node.find('.qunee-status').text(text);
        };
      };

      var onPushNodeData = function(data) {
        $scope.logList = $scope.logList || [];
        // $scope.logList.push(data.log);
        data.log.created_at = DateParseServ.dateParse(data.log.created_at);
        $scope.logList.push(data.log);
        console.log(data);
        var selfJson = JSON.parse($scope.getChartJSON());

        // 保存组内节点
        var groupNodes = [];
        selfJson.datas.map(function(selfItem, index) {

          if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
            groupNodes.push({
              index: index,
              item: selfItem,
              ref: selfItem.json.properties.data.$ref
            });
          };
        });

        // 更新节点数据 只会改变单个节点
        selfJson.datas.map(function(selfItem, index) {

          // 更新普通节点
          if (selfItem._className === 'Q.Node') {

            if (!!selfItem.json.properties.data.id) {

              if (selfItem.json.properties.data.id === data.node.id) {
                selfItem.json.properties.data.infoData.status = data.node.status;
                updateNode = selfItem.json.properties.data;
                getNodeData(selfItem.json.properties.data, selfItem.json);
                $scope.isShowDialog = (data.node.status === 'running' && selfItem.json.properties.data.infoData.type === 'userConfirmNode');

                if ($scope.isShowDialog) {
                  $scope.quneeState = 'waitConfirmOrSubmit';
                  $scope.socketPullData('pause');
                };
              };
            };
          };
        });

        updateJSON(selfJson);

        if ($scope.isShowDialog) {
          $scope.userConfirmModel.id = updateNode.id;
          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
          });
          strapModal.$promise.then(strapModal.show);
        };
        updateQuneeStateBtn();



      };

      var onQuneeInfo = function(evt, data) {
        $scope.$apply(function() {
          $scope.processInfoState = true;
          $scope.historyListState = false;
          $scope.nodeInfoState = false;
        });
      };

      var onQuneeHistory = function(evt, data) {
        $scope.$apply(function() {
          $scope.historyListState = true;
          $scope.processInfoState = false;
          $scope.nodeInfoState = false;
        });
      };

      // 检测
      var onQuneeCheck = function(evt, data) {

        if ($scope.stateConfig.check) {
          $scope.quneeState = 'check';

          // 改变流程摁键组的状态
          updateQuneeStateBtn();

          // 改变流程状态标示的状态
          $scope.socketPullData('requesting');
          ManagerProcessQuneeServ.ManagerProcessQuneeCheck({
            id: processId
          })
          .then(function(ret) {
            $timeout(function () {

              if (ret.status === 200) {
                $scope.quneeState = 'checkSuccess';
              } else {
                $scope.quneeState = 'checkError';
              };

              // 改变流程状态标示的状态
              $scope.socketPullData($scope.quneeState);
              updateQuneeStateBtn();
            }, 2000);
          });

        };
      };

      // 点击执行
      var onQuneeStart = function(evt, data) {

        if ($scope.stateConfig.start) {

          // 改变流程状态标示的状态
          $scope.socketPullData('requesting');
          $node.find('.qunee-start').addClass('default btn-outline');
          $timeout(function() {
            ManagerProcessQuneeServ.ManagerProcessQuneeStart({
              id: processId
            })
            .then(function(ret) {

              if (ret.status === 200) {
                var updateNode;
                $node.find('.qunee-start').removeClass('default btn-outline');
                ParseMapServ.setItem(processId, ret.results.pl_ex_id, 'process');
                execId = ParseMapServ.getItem(processId, 'process')
                // AlertServ.showSuccess(ret.msg);
                $scope.stateConfig.start = !!!$scope.stateConfig.start;
                $scope.quneeState = 'running';

                // 改变流程状态标示的状态
                $scope.socketPullData($scope.quneeState);
                updateQuneeStateBtn();

                // // 模拟socket推送的节点状态
                // quneeStart = $timeout(function() {
                //
                //   // socket更新的数据
                //   var socketData = {
                //
                //     // 改变的节点属性 (普通节点 , 组节点)
                //     // changeNodeList: {
                //     //   nodes: {
                //     //     id: 7,
                //     //     status: "running"
                //     //   }
                //     // },
                //
                //     changeNodeList: {
                //       nodes: {
                //         id: 3,
                //         status: "error"
                //       }
                //     },
                //
                //     // 流程状态
                //     status: 'userConfirmNode',
                //
                //     // 单条日志
                //     log: {}
                //   }
                //
                //   var selfJson = JSON.parse($scope.getChartJSON());
                //
                //   // 保存组内节点
                //   var groupNodes = [];
                //   selfJson.datas.map(function(selfItem, index) {
                //
                //     if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
                //       groupNodes.push({
                //         index: index,
                //         item: selfItem,
                //         ref: selfItem.json.properties.data.$ref
                //       });
                //     };
                //   });
                //
                //   // 更新节点数据 只会改变单个节点
                //   selfJson.datas.map(function(selfItem, index) {
                //
                //     // 更新普通节点
                //     if (selfItem._className === 'Q.Node') {
                //
                //       if (!!selfItem.json.properties.data.id) {
                //
                //         if (selfItem.json.properties.data.id === data.node.id) {
                //           selfItem.json.properties.data.infoData.status = data.node.status;
                //           updateNode = selfItem.json.properties.data;
                //           getNodeData(selfItem.json.properties.data, selfItem.json);
                //           $scope.isShowDialog = (data.node.status === 'running' && selfItem.json.properties.data.infoData.type === 'userConfirmNode');
                //
                //           if ($scope.isShowDialog) {
                //             $scope.quneeState = 'waitConfirmOrSubmit';
                //             $scope.socketPullData('pause');
                //           };
                //         };
                //       };
                //     };
                //   });
                //
                //   updateJSON(selfJson);
                //
                //   if ($scope.isShowDialog) {
                //     $scope.userConfirmModel.id = updateNode.id;
                //     strapModal = DialogServ.modal({
                //       'scope': $scope,
                //       'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
                //     });
                //     strapModal.$promise.then(strapModal.show);
                //   };
                //   updateQuneeStateBtn();
                // }, 2000);
              } else {
                AlertServ.showError(ret.msg);
              };
            });
          }, 2000);
        };
      };

      // 暂停
      var onQuneePause = function(evt, data) {

        if ($scope.stateConfig.pause) {
          $scope.socketPullData('requesting');
          $node.find('.qunee-pause').addClass('default btn-outline');

          ManagerProcessQuneeServ.ManagerProcessQuneePause({
            id: execId
          })
          .then(function(ret) {

            if (ret.status === 200) {
              $timeout(function() {
                $node.find('.qunee-pause').removeClass('default btn-outline');
                $scope.quneeState = 'pause';
                $scope.socketPullData($scope.quneeState);
                updateQuneeStateBtn();
                AlertServ.showSuccess(ret.msg);
              }, 2000);
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        };
      };

      // 继续
      var onQuneeContinue = function(evt, data) {

        if ($scope.stateConfig.continue) {
          var updateNode;
          $scope.socketPullData('requesting');
          $node.find('.qunee-continue').addClass('default btn-outline');
          ManagerProcessQuneeServ.ManagerProcessQuneeContinue({
            id: execId
          })
          .then(function(ret) {

            if (ret.status === 200) {
              $scope.quneeState = 'running';
              $timeout(function() {
                $node.find('.qunee-continue').removeClass('default btn-outline');
                $scope.socketPullData($scope.quneeState);
                updateQuneeStateBtn();
              }, 2000);

              // // 模拟socket推送的节点状态
              // quneeStart = $timeout(function() {
              //
              //   // socket更新的数据
              //   var socketData = {
              //
              //     // 改变的节点属性 (普通节点 , 组节点)
              //     changeNodeList: {
              //       nodes: {
              //         id: 7,
              //         status: "running"
              //       }
              //     },
              //
              //     // 流程状态
              //     status: 'userConfirmNode',
              //
              //     // 单条日志
              //     log: {}
              //   }
              //
              //   var selfJson = JSON.parse($scope.getChartJSON());
              //
              //   // 保存组内节点
              //   var groupNodes = [];
              //   selfJson.datas.map(function(selfItem, index) {
              //
              //     if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
              //       groupNodes.push({
              //         index: index,
              //         item: selfItem,
              //         ref: selfItem.json.properties.data.$ref
              //       });
              //     };
              //   });
              //
              //   // 更新节点数据 只会改变单个节点
              //   selfJson.datas.map(function(selfItem, index) {
              //
              //     // 更新普通节点
              //     if (selfItem._className === 'Q.Node') {
              //
              //       if (!!selfItem.json.properties.data.id) {
              //
              //         if (selfItem.json.properties.data.id === data.node.id) {
              //           selfItem.json.properties.data.infoData.status = data.node.status;
              //           updateNode = selfItem.json.properties.data;
              //           getNodeData(selfItem.json.properties.data, selfItem.json);
              //           $scope.isShowDialog = (data.node.status === 'running' && selfItem.json.properties.data.infoData.type === 'userConfirmNode');
              //
              //           if ($scope.isShowDialog) {
              //             $scope.quneeState = 'waitConfirmOrSubmit';
              //             $scope.socketPullData('pause');
              //           };
              //         };
              //       };
              //     };
              //   });
              //
              //   updateJSON(selfJson);
              //
              //   if ($scope.isShowDialog) {
              //     $scope.userConfirmModel.id = updateNode.id;
              //     strapModal = DialogServ.modal({
              //       'scope': $scope,
              //       'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
              //     });
              //     strapModal.$promise.then(strapModal.show);
              //   };
              //   updateQuneeStateBtn();
              // }, 4000);
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        };
      };

      // 终止
      var onQuneeQuit = function(evt, data) {

        if ($scope.stateConfig.quit) {

          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorQuit.html'
          });
          strapModal.$promise.then(strapModal.show);
        };
      };

      // 跳过本节点
      var onQuneeSkipSelfNode = function(evt, data) {

        if (!!!data.disabled) {
          ManagerProcessQuneeServ.ManagerProcessQuneeSkipSelfNode()
          .then(function(ret) {
            console.log(ret);
          });
        };
      };

      // 重做本节点
      var onQuneeRestartSelfNode = function(evt, data) {
        $scope.isShowDialog = (!!(data.type === 'userConfirmNode' && data.status === 'running'));

        if ($scope.isShowDialog) {
          $scope.userConfirmModel.id = data.id;
          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
          });
          strapModal.$promise.then(strapModal.show);
        } else {
          ManagerProcessQuneeServ.ManagerProcessQuneeResetNode({
            id: execId,
            node_id: data.id
          })
          .then(function(ret) {

            if (ret.status === 200) {
              AlertServ.showSuccess(ret.msg);
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        }
        $scope.quneeState = 'waitConfirmOrSubmit';
        $scope.socketPullData('pause');
        updateQuneeStateBtn();
      };

      // 手工接管
      var onQuneeManualNozzleNode = function(evt, data) {

        if (!!!data.disabled) {
          $scope.userEditorTakeOverModel.id = data.id;
          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorTakeOver.html'
          });
          strapModal.$promise.then(strapModal.show);
        };
      };

      // 切换日志显示状态
      var toggleLog = function() {
        $scope.logShowState = !!!$scope.logShowState;
      };

      var getNodeData = function(data, node, isGroup) {
        var type, status, info;

        if (isGroup) {
          type = quneeRefTypeMap[data.infoData.ref_type];

          if (node.status && typeof node.status === 'string') {
            status = node.infoData.status;
          } else {
            status = nodeStatusMap[node.status] || 'init';
          };
          info = $scope.statusNodeMap[type][status];
          data.image = info.icon;
          data.menuList = info.menuList;
          data.status = status;
          data.type = type;
        } else {
          type = data.infoData.type || quneeRefTypeMap[data.infoData.ref_type];

          if (data.infoData.status && typeof data.infoData.status === 'string') {
            status = data.infoData.status;
          } else {
            status = nodeStatusMap[data.infoData.status] || 'init';
          };
          info = $scope.statusNodeMap[type][status];

          if (info) {
            node.image = info.icon;
            node.menuList = info.menuList;
          };
        };

        console.log('info', info);
      };

      // 创建直线
      var createEdge = function(graph, from, to, pathSegmentList) {
        var edge = graph.createEdge('edge', from, to);
        pathSegmentList && pathSegmentList.map(function(item) {
          edge.addPathSegment([item.x, item.y]);
        });
        return edge;
      };


      // 创建组节点
      var createGroup = function (groupData, expanded, graph) {
        var graph = graph || $window.editor.graph;
        expanded = expanded !== false;
        var group = graph.createGroup(groupData.name);

        group.expanded = expanded;
        var groupHandle = new Q.LabelUI(expanded ? "-" : "+");
        groupHandle.backgroundColor = "#2898E0";
        groupHandle.color = "#FFF";
        groupHandle.padding = new Q.Insets(0, 4);
        groupHandle.borderRadius = 0;
        groupHandle.position = Q.Position.RIGHT_TOP;
        groupHandle.anchorPosition = Q.Position.LEFT_TOP;
        groupHandle.type = "GroupHandle";
        groupHandle.reverseExpanded = function(evt){
            var g = this.parent.data;
            g.expanded = !g.expanded;
        }
        group.addUI(groupHandle, {
            property : "expanded",
            callback: function(value, ui){
                ui.data = value ? "-" : "+";
            }
        });
        return group;
      };

      // 解析json
      var translateToQuneeElements = function(json, graph){
          var map = {};
          var graph = graph || $window.editor.graph;

          // 创建普通节点
          if (json.nodes) {
              Q.forEach(json.nodes, function(data){
                  var node = graph.createNode(data.name, data.x || 0, data.y || 0);
                  getNodeData(data, node);
                  node.set("data", data);
                  map[data.id] = node;
              });
          };

          // 创建组
          if (json.groups) {
              Q.forEach(json.groups, function(data){
                  var group = createGroup(data, true, graph);
                  getNodeData(data, group);
                  data.nodes.map(function(item){

                    // 子组
                    var innerNode = graph.createNode(item.name, item.x, item.y);
                    getNodeData(item, innerNode);
                    innerNode.set("data", item);
                    map[item.id] = innerNode;
                    group.addChild(innerNode);
                  });

                  group.set("data", data);
                  map[data.id] = group;
              });
          };

          // 创建连线
          if (json.edges) {
              Q.forEach(json.edges, function(data){
                  var from = map[data.from];
                  var to = map[data.to];

                  if(!from || !to){
                      return;
                  };

                  // data.pathSegmentList = [
                  //   {
                  //     x: 100,
                  //     y: 200
                  //   }
                  // ];

                  var edge = createEdge(graph, from, to, data.infoData.pathList);
                  edge.set("data", data);
              }, graph);
          };
      };

      // 显示右侧信息
      var onShowNodeInfo = function(evt) {

        var data = evt.getData();

        // 是否点击到空白处
        if (!!!data) {
          $scope.$apply(function() {
            $scope.historyListState = false;
            $scope.processInfoState = false;
            $scope.nodeInfoState = false;
          });
          return false;
        } else {
          console.log('getQuneeNodeInfo');
          // $scope.getQuneeNodeInfo(data);
        };

        if (data instanceof Q.Group) {
            var target = $window.editor.graph.hitTest(evt);

            if (target && target.type == "GroupHandle") {
                target.reverseExpanded();
            };
        };
      };

      var initQuneeEvent = function() {
        editor.graph.onclick = onShowNodeInfo;
      };

      // 获取加载完成的json
      var getChartJSON = function() {
        return editor.graph.exportJSON(true, {space: '  '});
      };

      var initEditor = function(callback) {
        $node.find('.editor').graphEditor({
          callback: function(editor){
            translateToQuneeElements($scope.nodeList, editor.graph);
            editor.graph.moveToCenter();
            editor.graph.zoomToOverview();
            $window.editor = editor;
            var selfJson = JSON.parse($scope.getChartJSON());
            console.log('selfJson', selfJson);
            initQuneeEvent();
            callback && callback();
          }
        });
      };

      // 局部刷新流程图
      var updateJSON = function(data) {
        // $scope.logInfo = data;

        // translateToQuneeElements(data);
        editor.submitJSON(data);
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
        $window.$quneeNode = $node;
      };

      var bindListener = function() {
        $scope.getQuneeNodeInfo = getQuneeNodeInfo;
        $scope.getQuneeProcessInfo = getQuneeProcessInfo;
        $scope.getQuneeHistoryList = getQuneeHistoryList;
        $scope.getManagerProcessQuneeLogList = getManagerProcessQuneeLogList;
        $scope.getUserList = getUserList;
        $scope.createGroup = createGroup;
        $scope.translateToQuneeElements = translateToQuneeElements;
        $scope.initEditor = initEditor;
        $scope.updateJSON = updateJSON;
        $scope.getChartJSON = getChartJSON;
        $scope.initQuneeEvent = initQuneeEvent;
        $scope.toggleLog = toggleLog;
        $scope.getQuneeState = getQuneeState;
        $scope.getQuneeStateAndData = getQuneeStateAndData;
        $scope.getQuneeExecState = getQuneeExecState;
        $scope.submitUserConfirm = submitUserConfirm;
        $scope.activeUser = activeUser;
        $scope.submitEditorTakeOver = submitEditorTakeOver;
        $scope.submitProcessQuit = submitProcessQuit;
        $scope.socketPullData = socketPullData;

        // 监听qunee 所有事件
        $node.on('qunee.check', onQuneeCheck);
        $node.on('qunee.start', onQuneeStart);
        $node.on('qunee.pause', onQuneePause);
        $node.on('qunee.continue', onQuneeContinue);
        $node.on('qunee.quit', onQuneeQuit);
        // $node.on('qunee.onlyExecuteSelfNode', onQuneeOnlyExecuteSelfNode);
        // $node.on('qunee.fromExecuteSelfNode', onQuneeFromExecuteSelfNode);
        $node.on('qunee.skipSelfNode', onQuneeSkipSelfNode);
        $node.on('qunee.restartSelfNode', onQuneeRestartSelfNode);
        $node.on('qunee.manualNozzleNode', onQuneeManualNozzleNode);
        $node.on('qunee.stateChange', onStateChange);

        $node.on('qunee.info', onQuneeInfo);
        $node.on('qunee.history', onQuneeHistory);
      };

      var initPlugins = function() {

        window.historyProcess = true;

        $scope.logList = [];


        // 只监听跳转路由
        $rootScope.$on('$stateChangeStart', function() {
          console.log('跳转路由 清除执行id 下次进来');
          console.log('状态', $scope.quneeState);

          // 如果状态不为终止 执行成功 的话 则清除执行id
          if ($scope.quneeState === 'manualQuit' || $scope.quneeState === 'execSuccess') {
            ParseMapServ.removeItem(processId, 'quitState');
            ParseMapServ.removeItem(processId, 'process');
          };
        });

        // 保存当前流程id
        execId = $stateParams.id;
        processId = $stateParams.processId;
        // execId = ParseMapServ.getItem(processId, 'process') || 0;
        $scope.getManagerProcessQuneeLogList(execId);
        // 用户确认数据
        $scope.userConfirmModel = {
          errerMsg: '提示：用户确认超时2分钟。'
        };
        $scope.selectDefaultText = '请选择用户';
        $scope.stateConfig = {
          check: true,
          start: true,
          pause: true,
          quit: true
        };

        // 用户接管表单参数
        $scope.userEditorTakeOverModel = {
          check: 1,
          resultQuery: true,
          remark: ''
        };

        $scope.userEditorQuitModel = {
          remark: ''
        };

        // 初始化参数
        $scope.historyListState = false;
        $scope.nodeInfoState = false;
        $scope.logShowState = false;
        $scope.processInfoState = false;

        // 所有节点状态字典
        ManagerProcessQuneeServ.getManagerProcessQuneeStateMap()
        .then(function(result) {
          $scope.statusNodeMap = result;
          $window.statusNodeMap = result;
          getQuneeStateAndData();
        });

        // $scope.getUserList();
        // $scope.getQuneeHistoryList();
        $scope.getQuneeProcessInfo();
        $node.find('.htrd-c-button-group').eq(0).hide();
        $node.find('.qunee-history').hide();

        // 初始化socket链接
        // SocketServ.initSocket(processId);
        // SocketServ.onMessage(onPushNodeData);
      };

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'config': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/quneeInfoHistory.html'
  };
}]);
